package cn.getech.data.development.utils;

import cn.getech.data.development.dto.EsDto;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;


import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpHost;


import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.*;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @ClassName EsUtil
 * @Description TODO
 * @Author Getech
 * @Date 2021/1/11 10:26
 */
public class EsUtil {

    /**
    * @Description  获取es连接客户端
    * @Author  chengweiping
    * @Date   2021/1/11 10:45
    */
   /* public static TransportClient getTransportClient(EsDto esDto){
        TransportClient transportClient=null;
        try {
            String clusterName=esDto.getClusterName();
            String ip=esDto.getIp();
            String portStr=esDto.getPort();
            Integer port=Integer.parseInt(portStr);
            Settings settings = Settings.builder().put("cluster.name", clusterName).build();
            TransportClient client = new PreBuiltTransportClient(settings)
                    .addTransportAddresses(new TransportAddress(InetAddress.getByName(ip), port));
            System.out.println(client.toString());
        } catch (UnknownHostException e) {
            e.printStackTrace();
            transportClient=null;
        }
        return transportClient;
    }*/



    /**
    * @Description 获取es高级客户端
    * @Author  chengweiping
    * @Date   2021/1/12 14:33
    */
    public static RestHighLevelClient  getHighClient(EsDto esDto) throws Exception {
//        RestHighLevelClient  client=null;
//        try{
//            String username=esDto.getUsername();
//            String password=esDto.getPassword();
//
//            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
//            credentialsProvider.setCredentials(AuthScope.ANY,
//                    new UsernamePasswordCredentials(username, password));  //es账号密码
//
//            String ip=esDto.getIp();
//            String portStr=esDto.getPort();
//            Integer port=Integer.parseInt(portStr);
//            RestClientBuilder builder = RestClient.builder(new HttpHost(ip, port, "http"))
//                    .setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() {
//                        @Override
//                        public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder requestConfigBuilder) {
//                            requestConfigBuilder.setConnectTimeout(10000);
//                            requestConfigBuilder.setSocketTimeout(10000);
//                            requestConfigBuilder.setConnectionRequestTimeout(10000);
//                            return requestConfigBuilder;
//                        }
//                    }).setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
//                        @Override
//                        public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
//                            httpClientBuilder.disableAuthCaching();
//                            return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
//                        }
//                    });
//                 client= new RestHighLevelClient(builder);
//                 //先获取存在的索引
//                List<String> indexList= getIndexList(client);
//                if(CollectionUtil.isNotEmpty(indexList)){
//                    //此处是用逗号隔开的索引
//                    String dbName=esDto.getDbname();
//                    if(StringUtils.isNotBlank(dbName)){
//                       List<String>  pageIndexList=Stream.of(dbName.split(",")).collect(Collectors.toList());
//                       for(String indexName:pageIndexList){
//                            //如果有个索引不存在则报异常
//                           if(!indexList.contains(indexName)){
//                               throw  new Exception("索引"+indexName+"不存在");
//                           }
//                       }
//
//                    }
//
//                }
//
//        }catch (Exception e){
//            e.printStackTrace();
//            client=null;
//            throw e;
//        }
//        System.out.println(client.toString());
//        return client;
        return null;
    }


//    /**
//    * @Description 获取索引列表
//    * @Author  chengweiping
//    * @Date   2021/1/12 14:48
//    */
//    public static  List<String> getIndexList(RestHighLevelClient restHighLevelClient) throws Exception {
//        List<String> resultList = new ArrayList<>();
//        try{
//            GetAliasesRequest request = new GetAliasesRequest();
//            GetAliasesResponse alias = restHighLevelClient.indices().getAlias(request, RequestOptions.DEFAULT);
//            Map<String, Set<AliasMetaData>> map = alias.getAliases();
//            map.forEach((k, v) -> {
//                if (!k.startsWith(".")) {//忽略elasticesearch 默认的
//             /*   Map map1 = new HashMap();
//                map1.put("indexName", k);*/
//                    resultList.add(k);
//                }
//            });
//
//        }catch (Exception e){
//            e.printStackTrace();
//            if(e.getMessage().contains("UnknownHostException")){
//                throw new Exception("主机填写有误");
//            }else if(e.getMessage().contains("ConnectException")){
//                throw new Exception("请检查主机、端口以及用户名、密码");
//            }else if (e.getMessage().contains("authenticate")){
//                throw new Exception("用户名或密码错误");
//            }else{
//                throw e;
//            }
//
//
//        }
//        System.out.println(JSON.toJSON(resultList));
//        return resultList;
//        //[{"indexName":"%{test222}"},{"indexName":"test"}]
//    }


    /**
     * 判断索引是否存在
     *
     * @param index
     * @return
     */
    public static boolean isIndexExist(String index,RestHighLevelClient client) throws IOException {

        GetIndexRequest request = new GetIndexRequest(index);

        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);

        return exists;
    }

    /**
     * 高亮结果集 特殊处理
     * map转对象 JSONObject.parseObject(JSONObject.toJSONString(map), Content.class)
     * @param searchResponse
     * @param highlightField
     */
    public static List<Map<String, Object>> setSearchResponse(SearchResponse searchResponse, String highlightField) {
        //解析结果
        ArrayList<Map<String,Object>> list = new ArrayList<>();
        for (SearchHit hit : searchResponse.getHits().getHits()) {
            Map<String, HighlightField> high = hit.getHighlightFields();
            HighlightField title = high.get(highlightField);

            hit.getSourceAsMap().put("id", hit.getId());

            Map<String, Object> sourceAsMap = hit.getSourceAsMap();//原来的结果
            //解析高亮字段,将原来的字段换为高亮字段
            if (title!=null){
                Text[] texts = title.fragments();
                String nTitle="";
                for (Text text : texts) {
                    nTitle+=text;
                }
                //替换
                sourceAsMap.put(highlightField,nTitle);
            }
            list.add(sourceAsMap);
        }
        return list;
    }
}
